<template>
  <div class="columnModel" id="columnModel">
    <!-- 功能按钮 -->
    <div class="columnModel_button">
      <a-button class="addButton" :disabled="!btnPerm.includes('creatAble')" @click="addRecord" type="primary">
        <template #icon>
          <span class="iconfont icon-Add iconadd"></span>
        </template>
        新建
      </a-button>
      <div class="searchContent">
        <a-input v-model:value="searchName" placeholder="搜来源名称" style="width: 192px">
          <template #suffix>
            <i class="iconfont icon-search" @click="onSearch"></i>
          </template>
        </a-input>
      </div>
    </div>
    <!-- 表格展示部分 -->
    <baseTable :columns="columns.sourceManageColumns" :dataSource="configData.records" :isSelect="true" :scroll="scroll"
      ref="searchBaseTables" :isShowPagination="isShowPagination" :showCheckDelete="showCheckDelete"
      :total="configData.total" @deleteRecord="deleteSelectedAll" @changePage="changePage">
      <template #bodyCell="{ column, text, record }">
        <template v-if="column.ellipsis">
          <table-tool-tip :text="text" :column="column"></table-tool-tip>
        </template>
        <template v-if="column.dataIndex === 'oparation'">
          <a class="eidtRecords" :class="{ disable: !btnPerm.includes('editAble') }"  @click="eidtRecord(record)">{{ record.oparation[0] }}</a>
          <a-popconfirm placement="topRight" 
          :disabled="!btnPerm.includes('deleteAble')"
          @confirm="confirmDelete(record)">
            <template #title>
              <p style="width: 197px">是否删除此来源</p>
            </template>
            <a :class="{ disable: !btnPerm.includes('editAble') }">{{ record.oparation[1] }}</a>
          </a-popconfirm>
        </template>
        <template v-if="column.dataIndex === 'defaulted'">
          <a-switch @click="switchChange(record, 1)" size="small" v-model:checked="record.defaulted" />
        </template>
        <template v-if="column.dataIndex === 'newWindow'">
          <a-switch @click="switchChange(record, 2)" size="small" v-model:checked="record.newWindow" />
        </template>
      </template>
      <template #otherOpration>
        <a-button :style="{ 'margin-left': '8px' }" @click="deleteSelectedAll"
          :disabled="!rowSelection.length || !btnPerm.includes('deleteAble')">删除</a-button>
      </template>
    </baseTable>
    <!-- 新建来源名称模态框 -->
    <base-modal :width="modAlProps.width" :isVisible="isVisible" :title="modAlProps.title" :buttons="buttons"
      @handleOk="buttonMessage" @handleCancle="isVisible = false" class="tagword_modal">
      <template v-slot:body>
        <a-form name="advanced_search" class="ant-advanced-search-form" autoComplete="off" :model="formState"
          ref="cloumnModelFrom">
          <a-form-item :name="['sourceName', 'value']" :label="formState.sourceName.label"
            :rules="[formState.sourceName.rule]">
            <a-input v-model:value="formState.sourceName.value" show-count :maxlength="25" allow-clear
              placeholder='请输入' />
          </a-form-item>
          <a-form-item :name="['sourceLink', 'value']" :label="formState.sourceLink.label"
            :rules="[formState.sourceLink.rule]">
            <a-input v-model:value="formState.sourceLink.value" placeholder='请输入' show-count :maxlength="100"
              allow-clear />
          </a-form-item>
          <a-form-item :name="['newWindow', 'value']" :label="formState.newWindow.label"
            :rules="[formState.newWindow.rule]">
            <a-radio-group v-model:value="formState.newWindow.value">
              <a-radio :value="true">是</a-radio>
              <a-radio :value="false">否</a-radio>
            </a-radio-group>
          </a-form-item>
          <a-form-item :name="['defaulted', 'value']" :label="formState.defaulted.label"
            :rules="[formState.defaulted.rule]">
            <a-radio-group v-model:value="formState.defaulted.value">
              <a-radio :value="true">是</a-radio>
              <a-radio :value="false">否</a-radio>
            </a-radio-group>
          </a-form-item>
        </a-form>
      </template>
    </base-modal>
  </div>
</template>
<script lang="ts" setup>
import { ref, reactive, computed, onMounted, nextTick, createVNode } from "vue";
import baseTable from "@/components/table/baseTable.vue";
import tableToolTip from "@/components/table/tableToolTip.vue";
import columns from "@/components/table/tableConfig/columnsName";
import { getTableScroll } from "@/components/table/tableConfig/table";
import baseModal from "@/components/modal/baseModal.vue";
import msgModal from "@/components/modal/modelConfig/MsGModal";
import { Modal, message } from "ant-design-vue";
import request from "@/api/index";
import { scrollType, modeProp } from "@/type.d";
import { checkSourceWord } from "./formRuler";
import {routerPerm} from '@/utils/common';
// type
type configDataType = {
  total: number;
  size: number;
  records: any[];
};
interface dataSourceType {
  [propName: string]: any;
}

//data
const btnPerm = ref<any[]>([]);
let scroll: scrollType = reactive({ y: "", isFixed: false }); // 表单滚动设置
const isShowPagination = true; // 是否需要配分页器
const showCheckDelete = true; // 是否需要分页器中的自定义全选和删除
let datas = reactive<dataSourceType>({});
//表格数据
let configData = reactive<configDataType>({ total: 0, size: 10, records: [] });
const searchBaseTables = ref<any>(null);
let rowSelection = ref<(string | number)[]>([]);
const deleteArr = ref<(string | number)[]>([]);
const searchName = ref<string>("");
// 当前页和数量
const pageCurrent = ref<number>(1);
const pageSize = ref<number>(10);
// 模态框数据
const isVisible = ref<boolean>(false);
const modAlProps: modeProp = reactive({
  width: "M",
  title: "新建来源",
});
const cloumnModelFrom = ref<any>("cloumnModelFrom");
const formState = reactive<dataSourceType>({
  sourceName: {
    value: "",
    rule: {
      required: true,
      validator: checkSourceWord,
      trigger: ["blur"],
      msg1: "来源名称不可为空！",
      msg2: "来源名称已存在！",
      api: "fetchSysSourceUniqueName",
      params: { id: undefined },
    },
    label: "来源名称",
  },
  sourceLink: {
    value: "",
    rule: {
      required: true,
      trigger: ["blur"],
      message: "来源链接不可为空！",
      params: {},
    },
    label: "来源链接",
  },
  newWindow: {
    value: 0,
    rule: {
      required: false,
    },
    label: "是否新窗口打开",
  },
  defaulted: {
    value: false,
    rule: {
      required: false,
    },
    label: "是否设为默认来源",
  },
  id: "",
});
const buttons = ref<dataSourceType[]>([]); //模态框button按钮个数和文案修改
// computed
rowSelection = computed(() => {
  return searchBaseTables.value.selectedRowKeys;
});
//methods

//切换来源状态
const switchChange = (record: any, type: number) => {
  let params: dataSourceType = {
    id: record.id,
    status: type === 1 ? record.defaulted : '',
    openNewWindow: type === 2 ? record.newWindow : '',
  };

  request[type === 1 ? "fetchSysSourceDefaulted" : "fetchSysSourceNewWindow"](params)
    .then((res: any) => {
      if (res.code == "00000 00000") {
        getRdecord();
        message.success(res.message);
      } else {
        message.error(res.message);
      }
    })
    .catch((err: any) => {
      throw new Error(err);
    });
};

const addRecord = async (type: string) => {
  //新加来源名称模态框条件修改
  //添加来源名称数据
  isVisible.value = true;
  modAlProps.title = "新建来源";
  (formState.sourceName.value = ""),
    (formState.sourceLink.value = ""),
    (formState.sourceName.rule.params.id = undefined);
  (formState.defaulted.value = false),
    (formState.newWindow.value = false),
    (formState.id = undefined);
  buttons.value = [
    {
      text: "保存",
      "html-type": "submit",
      keepAlive: true,
    },
    {
      text: "保存并继续新建",
      "html-type": "submit",
      keepAlive: true,
    },
  ];
};

const eidtRecord = async (item: dataSourceType) => {
  if(!btnPerm.value.includes('editAble')) return
  //编辑来源名称数据
  const data = await request.fetchSysSourceDetail({ id: item.id });
  isVisible.value = true;
  modAlProps.title = "编辑来源";
  (formState.sourceName.value = data.sourceName),
    (formState.sourceLink.value = data.sourceLink),
    (formState.defaulted.value = data.defaulted),
    (formState.newWindow.value = data.newWindow),
    (formState.id = data.id),
    (formState.sourceName.rule.params.id = data.id);
  buttons.value = [
    {
      text: "保存",
      "html-type": "submit",
      keepAlive: true,
    },
  ];
};

const buttonMessage = async (msg: dataSourceType) => {
  // 新添或编辑来源名称调取接口
  //保存
  cloumnModelFrom.value
    .validate()
    .then(() => {
      let params: dataSourceType = {
        sourceName: formState.sourceName.value,
        sourceLink: formState.sourceLink.value,
        isDefault: formState.defaulted.value,
        openNewWindow: formState.newWindow.value,
        id: formState.id,
      };
      let type: string = modAlProps.title.includes("编辑") ? "Edit" : "Add";

      request[type === "Edit" ? "fetchSysSourceUpdate" : "fetchSysSourceAdd"](params)
        .then((res: any) => {
          if (res.code == "00000 00000") {
            getRdecord();
            message.success(res.message);
          } else {
            message.error(res.message);
          }
        })
        .catch((err: any) => {
          throw new Error(err);
        });
      isVisible.value = msg.text == "保存" ? false : true;
      if (isVisible.value) {
        formState.sourceName.value = ''
        formState.sourceLink.value = ''
        formState.defaulted.value = false
        formState.newWindow.value = false
      }
    })
    .catch(() => { });
};

const confirmDelete = async (item: any) => {
  // 删除单个来源
  deleteArr.value = [item.id];
  deleteRecords(deleteArr.value);
};

const deleteSelectedAll = async () => {
  //删除已选所有来源
  let keys = rowSelection.value;
  Modal.confirm(
    Object.assign({}, msgModal.confirm, {
      title: "您确定删除选中的来源？",
      content: "",
      icon: createVNode("i", {
        class: "iconfont icon-warn warning_ICON",

      }),
      okText: "确定",
      onOk: async () => {
        await deleteRecords(keys);
        Modal.destroyAll();
      },
      onCancel() {
        Modal.destroyAll();
      },
    })
  );
};
const deleteRecords = async (keys: (string | number)[] = []) => {
  // 调接口删除来源
  await request.fetchSysSourceDelete({ ids: keys }).then((res: any) => {
    if (res.code == "00000 00000") {
      getRdecord();
      message.success(res.message);
    } else {
      message.error(res.message);
    }
  });
};

const onSearch = async () => {
  //搜索获取数据参数配置
  getRdecord();
};
const getRdecord = async () => {
  // 获取表格数据
  const data: {} = {
    pageNumber: datas.pageNumber || pageCurrent.value,
    pageSize: datas.pageSize || pageSize.value,
    sourceName: searchName.value || "",
  };
  const telData = (await request.fetchSysSourcePage(data)) || {};
  let reqData = telData;
  let sourceData = ref<dataSourceType[]>([]);
  const records: any[] = [];
  reqData?.records?.map((item: any, index: number) => {
    sourceData = {
      ...item,
      oparation: ["编辑", "删除"],
      sourceName: item.sourceName,
      createTime: item.createTime,
      newWindow: item.openNewWindow,
      defaulted: item.isDefault,
      createUser: item.createUser,
      sourceLink: item.sourceLink,
      id: item.id,
    };
    records.push(sourceData);
  });
  configData.total = reqData.total;
  configData.size = reqData.size;
  configData.records = records;
  searchBaseTables.value.selectedRowKeys = [];
  nextTick(() => {
    scroll.y = getTableScroll(74, "columnModel").y;
    scroll.isFixed = getTableScroll(74, "columnModel").isFixed;
  });
};

//切换分页器
const changePage = (data: { pageCurrent: any; pageSize: any }) => {
  datas = {
    pageNumber: data.pageCurrent,
    pageSize: data.pageSize,
  };
  getRdecord();
};
//onmounted
onMounted(() => {
  btnPerm.value = routerPerm()
  getRdecord();
});
</script>
<style lang="scss" scoped>
.columnModel {
  width: 100%;
  height: calc(100% - 72px);
  padding: 16px;
  background-color: #fff;
  overflow: hidden;

  .columnModel_button {
    padding-bottom: 16px;
    display: flex;
    justify-content: space-between;

    .addButton {
      display: flex;
      align-items: center;
      margin-right: 8px;

      .iconadd {
        font-size: 24px;
        margin-right: 4px;
      }
    }

    .importButton {
      font-weight: 400;
      color: rgba(0, 0, 0, 0.85);
      margin-right: 8px;
    }

    .modelSelect {
      margin-left: auto;
      margin-right: 10px;
      font-size: 14px;
      font-weight: 400;
      color: rgba(0, 0, 0, 0.85);
    }

    .modelSelectStatus {
      margin-left: 4px;
      margin-right: 10px;
      font-size: 14px;
      font-weight: 400;
      color: rgba(0, 0, 0, 0.85);
    }

    .searchContent {
      margin-right: 0px;

      .icon-search {
        font-size: 20px;
        color: rgba(0, 0, 0, 0.45);
        position: absolute;
        right: 12px;
        top: 0px;
      }
    }
  }

  :deep(.ant-table-thead .ant-table-cell:nth-last-of-type(1)) {
    text-align: right;
    margin-right: 16px;
  }

  .eidtRecords {
    margin-right: 16px;
  }
}

.model-tip {
  margin-top: 8px;
  margin-left: 4px;
  font-size: 12px;
  font-weight: 400;
  color: rgba(0, 0, 0, 0.45);
}

.tag-item {
  margin-bottom: 0 !important;
}

:deep(.ant-form-item:nth-last-of-type(1)) {
  margin-left: 0px;
}

::v-deep(.ant-input-number) {
  width: 136px;
  margin-left: 4px;
}

::v-deep(.ant-input-affix-wrapper) {
  width: 464px;
  margin-left: 4px;
}

::v-deep(.ant-form-item) {
  display: flex;

  .ant-form-item-label {
    flex-grow: 0;
    width: 126px;
    text-align: right;
  }
}

::v-deep(.ant-select) {
  width: 96px;
}

::v-deep(.ant-form-item-control-input-content:hover) {
  .anticon-close-circle {
    display: block;
  }

  .ant-input-show-count-suffix {
    // display: none;
  }
}

::v-deep(.ant-btn) {
  padding: 4px 12px;
}
</style>
